from keras.applications.vgg16 import VGG16
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.vgg16 import preprocess_input
from keras.applications.vgg16 import decode_predictions
from keras import backend as k

conf = k.tf.ConfigProto(device_count={'CPU': 1},
                        intra_op_parallelism_threads=1,
                        inter_op_parallelism_threads=1)
k.set_session(k.tf.Session(config=conf))

import datetime
import logging
def predict(image_path):
    k.clear_session()
    model = VGG16(weights='imagenet', input_shape=(224, 224, 3),
                   pooling='max', include_top=True)

    image = load_img(image_path, target_size=(224, 224))

    start1 = datetime.datetime.now()
    image = img_to_array(image)  # output Numpy-array
    start2 = datetime.datetime.now()
    image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
    start3 = datetime.datetime.now()
    image = preprocess_input(image)
    start4 = datetime.datetime.now()
    feat = model.predict(image).round(6)
    start5 = datetime.datetime.now()
    labels = decode_predictions(feat, top=10)  # get top 10 labels
    start6 = datetime.datetime.now()
    labels = [i[1:2][0] for i in labels[0]]
    end = datetime.datetime.now()

    logging.info('{}, {}, {}, {}, {}, {}'.format(start2-start1, start3-start2, start4-start3, start5-start4, start6-start5, end-start6))

    return labels


if __name__ == '__main__':
    image_path = 'C:/Users/Administrator/Desktop/test.jpg'
    labels = predict(image_path)
    print(labels)
